package com.day08.homework.dao;

import com.day08.homework.utils.DataBaseConnection;
import com.day08.homework.utils.DataBaseConnectionFactory;
import com.day08.homework.vo.Book;

import java.util.List;

public class BookDAOProxy implements IBookDao {

    private DataBaseConnection dataBaseConnection = null;
    private IBookDao dao = null;

    public BookDAOProxy() {
        this.dataBaseConnection = DataBaseConnectionFactory.getDataBaseConnection();
        this.dao = new BookDaoImpl(dataBaseConnection.getConnection());
    }

    @Override
    public List<Book> selectBookInfoAll() throws Exception {
        List<Book> list = null;
        try {
            list = this.dao.selectBookInfoAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.dataBaseConnection.close();
        }
        return list;
    }

    @Override
    public List<Book> selectBookInfoLike(String bookName) throws Exception {
        List<Book> list = null;
        try {
            list = this.dao.selectBookInfoLike(bookName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.dataBaseConnection.close();
        }
        return list;
    }

    @Override
    public boolean insertBookInfo(Book book) throws Exception {
        boolean flag = false;
        try {
            if (!this.dao.selectBookInfoOne(book.getBookId()).equals(null)) {
                flag = this.dao.insertBookInfo(book);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.dataBaseConnection.close();
        }
        return flag;
    }

    @Override
    public boolean deleteBookInfo(Integer bookId) throws Exception {
        boolean flag = false;
        try {
            if (!this.dao.selectBookInfoOne(bookId).equals(null)) {
                flag = this.dao.deleteBookInfo(bookId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.dataBaseConnection.close();
        }
        return flag;
    }

    @Override
    public boolean updateBookInfo(Integer bookId, Book book) throws Exception {
        boolean flag = false;
        try {
            if (!this.dao.selectBookInfoOne(book.getBookId()).equals(null)) {
                flag = this.dao.updateBookInfo(bookId, book);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.dataBaseConnection.close();
        }
        return flag;
    }

    @Override
    public List<Book> selectBookInfoOne(Integer bookId) throws Exception {
        List<Book> list = null;
        try {
            list = this.dao.selectBookInfoOne(bookId);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.dataBaseConnection.close();
        }
        return list;
    }
}
